package com.ruoyi.zhgd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.StringUtils;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.zhgd.domain.*;
import com.ruoyi.zhgd.domain.vo.*;
import com.ruoyi.zhgd.dto.CollectPieceDto;
import com.ruoyi.zhgd.mapper.*;
import com.ruoyi.zhgd.service.IZjNWarningUserMessageService;
import com.ruoyi.zhgd.service.IZjNWarningUsingService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.zhgd.domain.bo.CollectDosageBo;
import com.ruoyi.zhgd.service.ICollectDosageService;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 消耗信息Service业务层处理
 *
 * @author zyb
 * @date 2023-09-20
 */
@Slf4j
@RequiredArgsConstructor
@Service
@DS("sjcj")
public class CollectDosageServiceImpl implements ICollectDosageService {

    private final CollectDosageMapper baseMapper;
    private final ZjNWarningUsingMapper warningUsingMapper;

    @Autowired
    private CollectPieceMapper pieceMapper;

    @Autowired
    private CollectProductMapper productMapper;

    @Autowired
    private ZjHntScaleMapper hntScaleMapper;

    @Autowired
    private  NWarningManagementMapper nWarningManagementMapper;

    @Autowired
    private ZjNWarningHntMapper zjNWarningHntMapper;

    @Autowired
    private IZjNWarningUserMessageService messageService;

    @Autowired
    private IZjNWarningUsingService zjNWarningUsingService;

    @Autowired
    private ZjHntMaterialStoreMapper materialStoreMapper;



    /**
     * 查询消耗信息
     */
    @Override
    public CollectDosageVo queryById(Long pkId){
        return baseMapper.selectVoById(pkId);
    }

    /**
     * 查询消耗信息列表
     */
    @Override
    public TableDataInfo<CollectDosageVo> queryPageList(CollectDosageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<CollectDosage> lqw = buildQueryWrapper(bo);
        Page<CollectDosageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询消耗信息列表
     */
    @Override
    public List<CollectDosageVo> queryList(CollectDosageBo bo) {
        LambdaQueryWrapper<CollectDosage> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<CollectDosage> buildQueryWrapper(CollectDosageBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<CollectDosage> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getParentPkId() != null, CollectDosage::getParentPkId, bo.getParentPkId());
        lqw.eq(bo.getPiece() != null, CollectDosage::getPiece, bo.getPiece());
        lqw.eq(StringUtils.isNotBlank(bo.getStorage()), CollectDosage::getStorage, bo.getStorage());
        lqw.eq(StringUtils.isNotBlank(bo.getMaterial()), CollectDosage::getMaterial, bo.getMaterial());
        lqw.eq(StringUtils.isNotBlank(bo.getSpec()), CollectDosage::getSpec, bo.getSpec());
        lqw.eq(bo.getWatFull() != null, CollectDosage::getWatFull, bo.getWatFull());
        lqw.eq(bo.getRecAmnt() != null, CollectDosage::getRecAmnt, bo.getRecAmnt());
        lqw.eq(bo.getPlanAmnt() != null, CollectDosage::getPlanAmnt, bo.getPlanAmnt());
        lqw.eq(bo.getFactAmnt() != null, CollectDosage::getFactAmnt, bo.getFactAmnt());
        lqw.eq(StringUtils.isNotBlank(bo.getFlag()), CollectDosage::getFlag, bo.getFlag());
        return lqw;
    }

    /**
     * 新增消耗信息
     */
    @Override
    public Boolean insertByBo(CollectDosageBo bo) {
        CollectDosage add = BeanUtil.toBean(bo, CollectDosage.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setPkId(add.getPkId());
        }
        return flag;
    }

    public  String test(String pkId) {
        //查询一盘数据
        log.info("pkid:" + pkId);
        List<CollectDosage> collectDosages = baseMapper.selectVoByPkId(pkId);
        if (collectDosages == null || collectDosages.size() == 0) {
            log.info("test/1没有查到盘数据");
            return "没有查到盘数据";
        }
        List<String> pkIds = collectDosages.stream().map(e -> e.getParentPkId().toString()).distinct().collect(Collectors.toList());
        List<ZjNWarningHnt> zjNWarningHntList = zjNWarningHntMapper.selectByPkId(pkIds);
        if (zjNWarningHntList.size() > 0) {
            log.info("test/2该条数据已经产生过报警");
            return "该条数据已经产生过报警!";
        }
        CollectProduct product = productMapper.selectByPkId(pkId);
        if (product == null) {
            log.info("test/3查询不到数据");
            return "查询不到数据";
        }
        String sd = "";
        String ss = "";
        String s11 = "";
        String s12 = "";
        String s13 = "";
        String deptId = null;
        //hntWarnErrorMap用于存储预警信息的误差值，拼接到短信里；g,z,c分别表示高级、中级、初级以区分预警等级；
        Map<String, String> hntWarnErrorMap = new HashMap<>();
        double scale;
        double errorValue;
        double percentError;
        for (CollectDosage collectDosage : collectDosages) {
            //查询名称部门等信息
            CollectPieceDto collectPieceDto = pieceMapper.selectBys(collectDosage.getParentPkId());
            log.info("collectPieceDto:", JsonUtils.toJsonString(collectPieceDto));
            /**
             * 按拌合站查询所有物料上下限；
             */
            LambdaQueryWrapper<ZjHntMaterialStore> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ZjHntMaterialStore::getIdentifier, product.getStationCode());
            List<ZjHntMaterialStore> materialStores = materialStoreMapper.selectList(queryWrapper);
            /**
             * 获取以物料名分组的map(上下限值)
             */
            Map<String, List<ZjHntMaterialStore>> materialNameMap = materialStores.stream().collect(Collectors.groupingBy(ZjHntMaterialStore::getMaterialStoreName));
            List<ZjHntMaterialStore> materialStore = materialNameMap.get(collectDosage.getMaterial());
            if (materialStore == null || materialStore.size() == 0) {
                log.info("没有查到料仓信息,料仓名称material：" + collectDosage.getMaterial() + "---pkId:" + pkId);
                ZjHntMaterialStore store = new ZjHntMaterialStore();
                store.setIdentifier(product.getStationCode());
                store.setMaterialStoreName(collectDosage.getMaterial());
                store.setStatus("0");
                store.setDelFlag("0");
                materialStoreMapper.insert(store);
                continue;
            }
            ZjHntMaterialStore hntMaterialStore = materialStore.get(0);
            Double upLimit;
            if (hntMaterialStore.getUpperLimit() == null && hntMaterialStore.getLowerLimit() == null) {
//                return "料仓信息没有设置上下限";
                log.info("料仓信息没有设置上下限,料仓名:"+hntMaterialStore.getMaterialStoreName()+"---PKID:"+pkId);
                continue;
            } else {
                upLimit = hntMaterialStore.getUpperLimit() == null ? hntMaterialStore.getLowerLimit() : hntMaterialStore.getUpperLimit();
            }
            Double recAmnt = collectDosage.getPlanAmnt();
            /**
             * 如果物料的配方值采集上来，就用采集的值，如果没有再查对应的配合比名称对应的物料陪防止；
             */
            if (recAmnt != null) {
                //误差值
                errorValue = collectDosage.getFactAmnt() - recAmnt;
                //误差百分比；
                percentError = errorValue * 100 / recAmnt;
                collectDosage.setScale(recAmnt);
                collectDosage.setErrorValue(errorValue);
                collectDosage.setPercentError(percentError);
                collectDosage.setUpdateTime(new Date());
                //多用或者少用的量
                Double c = collectDosage.getFactAmnt() - recAmnt;
                //如果在上下限范围内，跳出预警
                double limit = recAmnt * (upLimit / 100);
                if (Math.abs(c) <= limit) {
                    continue;
                }
                String error = String.format("%.2f", percentError) + "%";
                String uuid = String.valueOf(UUID.randomUUID());
                //查询混凝土报警
                deptId = collectPieceDto.getDeptId();
                Map<String, Object> map = new HashMap<>();
                map.put("typeId", 1);
                map.put("deptId", deptId);
                List<NWarningManagement> warningManagementList = nWarningManagementMapper.queryHntList(map);
                Map<String, NWarningManagement> warningManagementMap = warningManagementList.stream().collect(Collectors.toMap(NWarningManagement::getHntTypeName, e -> e));
                NWarningManagement nWarningManagement = warningManagementMap.get(hntMaterialStore.getMaterialStoreType());
                ZjNWarningHnt zjNWarningHnt = new ZjNWarningHnt();
                if (c > 0) {

                    if (nWarningManagement == null) {
                        log.info("test/5没有配置预警信息范围");
                        return "没有配置预警信息范围";
                    }
                    Double s = c - limit;
                    //算出百分比
                    BigDecimal a = BigDecimal.valueOf((s / recAmnt) * 100);
                    BigDecimal errors = a.setScale(2, BigDecimal.ROUND_HALF_UP);

                    if (a.compareTo(nWarningManagement.getDownAdvancedWarning()) >= 0) {
                        //高级报警
                        hntWarnErrorMap.put(uuid, error + ",g");
                        zjNWarningHnt.setId(uuid);
                        zjNWarningHnt.setWarningGrade("高级");
                        BeanUtils.copyProperties(collectPieceDto, zjNWarningHnt);
                        zjNWarningHnt.setMixingStation(collectPieceDto.getName());
                        zjNWarningHnt.setType(collectDosage.getMaterial());
                        zjNWarningHnt.setInsterTime(DateUtils.getNowDate());
                        zjNWarningHnt.setParentPkId(collectDosage.getParentPkId());
                        zjNWarningHnt.setError(errors.toString() + "%");
                        // 高级预警加处置状态为待处置。
                        // 盘序号
                        zjNWarningHnt.setSerial(collectPieceDto.getSerial());
                        zjNWarningHnt.setDisposalStatus(1);
                        zjNWarningHntMapper.insert(zjNWarningHnt);
                    } else if (a.compareTo(nWarningManagement.getDownMiddleWarning()) >= 0 && a.compareTo(nWarningManagement.getUpMiddleWarning()) == -1) {
                        //中级报警
                        hntWarnErrorMap.put(uuid, error + ",z");
                        zjNWarningHnt.setId(uuid);
                        zjNWarningHnt.setWarningGrade("中级");
                        BeanUtils.copyProperties(collectPieceDto, zjNWarningHnt);
                        zjNWarningHnt.setMixingStation(collectPieceDto.getName());
                        zjNWarningHnt.setType(collectDosage.getMaterial());
                        zjNWarningHnt.setInsterTime(DateUtils.getNowDate());
                        zjNWarningHnt.setParentPkId(collectDosage.getParentPkId());
                        zjNWarningHnt.setError(errors.toString() + "%");
                        // 盘序号
                        zjNWarningHnt.setSerial(collectPieceDto.getSerial());
                        zjNWarningHntMapper.insert(zjNWarningHnt);
                    } else if (a.compareTo(nWarningManagement.getDownLowWarning()) >= 0 && a.compareTo(nWarningManagement.getUpLowWarning()) == -1 && errors.compareTo(BigDecimal.ZERO) != 0) {
                        //初级报警
                        hntWarnErrorMap.put(uuid, error + ",c");
                        zjNWarningHnt.setId(uuid);
                        zjNWarningHnt.setWarningGrade("初级");
                        BeanUtils.copyProperties(collectPieceDto, zjNWarningHnt);
                        zjNWarningHnt.setMixingStation(collectPieceDto.getName());
                        zjNWarningHnt.setType(collectDosage.getMaterial());
                        zjNWarningHnt.setInsterTime(DateUtils.getNowDate());
                        zjNWarningHnt.setParentPkId(collectDosage.getParentPkId());
                        zjNWarningHnt.setError(errors.toString() + "%");
                        // 盘序号
                        zjNWarningHnt.setSerial(collectPieceDto.getSerial());
                        zjNWarningHntMapper.insert(zjNWarningHnt);
                    }
                } else {
                    if (nWarningManagement == null) {
                        log.info("test/6没有配置预警信息范围");
                        return "没有配置预警信息范围";
                    }
                    double s = c + limit;
                    BigDecimal a = BigDecimal.valueOf((s / recAmnt) * 100).abs();
                    BigDecimal errors = a.setScale(2, BigDecimal.ROUND_HALF_UP);
                    if (a.compareTo(nWarningManagement.getDownAdvancedWarning()) >= 0) {
                        //高级报警
                        hntWarnErrorMap.put(uuid, error + ",g");
                        zjNWarningHnt.setId(uuid);
                        zjNWarningHnt.setWarningGrade("高级");
                        BeanUtils.copyProperties(collectPieceDto, zjNWarningHnt);
                        zjNWarningHnt.setMixingStation(collectPieceDto.getName());
                        zjNWarningHnt.setType(collectDosage.getMaterial());
                        zjNWarningHnt.setInsterTime(DateUtils.getNowDate());
                        zjNWarningHnt.setParentPkId(collectDosage.getParentPkId());
                        zjNWarningHnt.setError(errors.toString() + "%");
                        // 高级预警加处置状态为待处置。
                        zjNWarningHnt.setDisposalStatus(1);
                        // 盘序号
                        zjNWarningHnt.setSerial(collectPieceDto.getSerial());
                        zjNWarningHntMapper.insert(zjNWarningHnt);
                    } else if (a.compareTo(nWarningManagement.getDownMiddleWarning()) >= 0 && a.compareTo(nWarningManagement.getUpMiddleWarning()) == -1) {
                        //中级报警
                        hntWarnErrorMap.put(uuid, error + ",z");
                        zjNWarningHnt.setId(uuid);
                        zjNWarningHnt.setWarningGrade("中级");
                        BeanUtils.copyProperties(collectPieceDto, zjNWarningHnt);
                        zjNWarningHnt.setMixingStation(collectPieceDto.getName());
                        zjNWarningHnt.setType(collectDosage.getMaterial());
                        zjNWarningHnt.setInsterTime(DateUtils.getNowDate());
                        zjNWarningHnt.setParentPkId(collectDosage.getParentPkId());
                        zjNWarningHnt.setError(errors.toString() + "%");
                        // 盘序号
                        zjNWarningHnt.setSerial(collectPieceDto.getSerial());
                        zjNWarningHntMapper.insert(zjNWarningHnt);
                    } else if (a.compareTo(nWarningManagement.getDownLowWarning()) >= 0 && a.compareTo(nWarningManagement.getUpLowWarning()) == -1 && errors.compareTo(BigDecimal.ZERO) != 0) {
                        //初级报警
                        hntWarnErrorMap.put(uuid, error + ",c");
                        zjNWarningHnt.setId(uuid);
                        zjNWarningHnt.setWarningGrade("初级");
                        BeanUtils.copyProperties(collectPieceDto, zjNWarningHnt);
                        zjNWarningHnt.setMixingStation(collectPieceDto.getName());
                        zjNWarningHnt.setType(collectDosage.getMaterial());
                        zjNWarningHnt.setInsterTime(DateUtils.getNowDate());
                        zjNWarningHnt.setParentPkId(collectDosage.getParentPkId());
                        zjNWarningHnt.setError(errors.toString() + "%");
                        // 盘序号
                        zjNWarningHnt.setSerial(collectPieceDto.getSerial());
                        zjNWarningHntMapper.insert(zjNWarningHnt);
                    }
                }
            } else {
                //查询手填的配比
                List<ZjHntScaleRef> zjHntScaleRefs = hntScaleMapper.selectByTypeStation(collectPieceDto.getRecipe(), product.getStationCode());
                if (zjHntScaleRefs == null || zjHntScaleRefs.size() == 0) {
                    log.info("test/4没有配比信息");
                    return "没有配比信息";
                }
                log.info("******************************************************zjHntScaleRefs.size:" + zjHntScaleRefs.size());
                for (ZjHntScaleRef zjHntScaleRef : zjHntScaleRefs) {
                    if (zjHntScaleRef.getMaterialDosage() > 0) {
                        if (zjHntScaleRef.getMaterialStoreName().equals(collectDosage.getMaterial())) {
                            //配比值()
                            scale = zjHntScaleRef.getMaterialDosage() * collectPieceDto.getPieAmnt();
                            //误差值
                            errorValue = collectDosage.getFactAmnt() - scale;
                            //误差百分比；
                            percentError = errorValue * 100 / scale;
                            collectDosage.setScale(scale);
                            collectDosage.setErrorValue(errorValue);
                            collectDosage.setPercentError(percentError);
                            collectDosage.setUpdateTime(new Date());
                            //多用或者少用的量
                            Double c = collectDosage.getFactAmnt() / collectPieceDto.getPieAmnt() - zjHntScaleRef.getMaterialDosage();
                            //如果在上下限范围内，跳出预警
                            double limit = zjHntScaleRef.getMaterialDosage() * (zjHntScaleRef.getUpperLimit() / 100);
                            if (Math.abs(c) <= limit) {
                                break;
                            }
                            String error = String.format("%.2f", percentError) + "%";
                            String uuid = String.valueOf(UUID.randomUUID());
                            //查询混凝土报警
                            deptId = collectPieceDto.getDeptId();
                            Map<String, Object> map = new HashMap<>();
                            map.put("typeId", 1);
                            map.put("deptId", deptId);
                            List<NWarningManagement> warningManagementList = nWarningManagementMapper.queryHntList(map);
                            Map<String, NWarningManagement> warningManagementMap = warningManagementList.stream().collect(Collectors.toMap(NWarningManagement::getHntTypeName, e -> e));
                            NWarningManagement nWarningManagement = warningManagementMap.get(zjHntScaleRef.getMaterialStoreType());
                            ZjNWarningHnt zjNWarningHnt = new ZjNWarningHnt();
                            if (c > 0) {
                                if (nWarningManagement == null) {
                                    log.info("test/5没有配置预警信息范围");
                                    return "没有配置预警信息范围";
                                }
                                Double s = c - limit;
                                //算出百分比
                                BigDecimal a = BigDecimal.valueOf((s / zjHntScaleRef.getMaterialDosage()) * 100);
                                BigDecimal errors = a.setScale(2, BigDecimal.ROUND_HALF_UP);
                                if (a.compareTo(nWarningManagement.getDownAdvancedWarning()) >= 0) {
                                    //高级报警
                                    hntWarnErrorMap.put(uuid, error + ",g");
                                    zjNWarningHnt.setId(uuid);
                                    zjNWarningHnt.setWarningGrade("高级");
                                    BeanUtils.copyProperties(collectPieceDto, zjNWarningHnt);
                                    zjNWarningHnt.setMixingStation(collectPieceDto.getName());
                                    zjNWarningHnt.setType(collectDosage.getMaterial());
                                    zjNWarningHnt.setInsterTime(DateUtils.getNowDate());
                                    zjNWarningHnt.setParentPkId(collectDosage.getParentPkId());
                                    zjNWarningHnt.setError(errors.toString() + "%");
                                    // 高级预警加处置状态为待处置。
                                    zjNWarningHnt.setDisposalStatus(1);
                                    // 盘序号
                                    zjNWarningHnt.setSerial(collectPieceDto.getSerial());
                                    zjNWarningHntMapper.insert(zjNWarningHnt);
                                } else if (a.compareTo(nWarningManagement.getDownMiddleWarning()) >= 0 && a.compareTo(nWarningManagement.getUpMiddleWarning()) == -1) {
                                    //中级报警
                                    hntWarnErrorMap.put(uuid, error + ",z");
                                    zjNWarningHnt.setId(uuid);
                                    zjNWarningHnt.setWarningGrade("中级");
                                    BeanUtils.copyProperties(collectPieceDto, zjNWarningHnt);
                                    zjNWarningHnt.setMixingStation(collectPieceDto.getName());
                                    zjNWarningHnt.setType(collectDosage.getMaterial());
                                    zjNWarningHnt.setInsterTime(DateUtils.getNowDate());
                                    zjNWarningHnt.setParentPkId(collectDosage.getParentPkId());
                                    zjNWarningHnt.setError(errors.toString() + "%");
                                    // 盘序号
                                    zjNWarningHnt.setSerial(collectPieceDto.getSerial());
                                    zjNWarningHntMapper.insert(zjNWarningHnt);
                                } else if (a.compareTo(nWarningManagement.getDownLowWarning()) >= 0 && a.compareTo(nWarningManagement.getUpLowWarning()) == -1 && errors.compareTo(BigDecimal.ZERO) != 0) {
                                    //初级报警
                                    hntWarnErrorMap.put(uuid, error + ",c");
                                    zjNWarningHnt.setId(uuid);
                                    zjNWarningHnt.setWarningGrade("初级");
                                    BeanUtils.copyProperties(collectPieceDto, zjNWarningHnt);
                                    zjNWarningHnt.setMixingStation(collectPieceDto.getName());
                                    zjNWarningHnt.setType(collectDosage.getMaterial());
                                    zjNWarningHnt.setInsterTime(DateUtils.getNowDate());
                                    zjNWarningHnt.setParentPkId(collectDosage.getParentPkId());
                                    zjNWarningHnt.setError(errors.toString() + "%");
                                    // 盘序号
                                    zjNWarningHnt.setSerial(collectPieceDto.getSerial());
                                    zjNWarningHntMapper.insert(zjNWarningHnt);
                                }
                            } else {
                                if (nWarningManagement == null) {
                                    log.info("test/6没有配置预警信息范围");
                                    return "没有配置预警信息范围";
                                }
                                double s = c + limit;
                                BigDecimal a = BigDecimal.valueOf((s / zjHntScaleRef.getMaterialDosage()) * 100).abs();
                                BigDecimal errors = a.setScale(2, BigDecimal.ROUND_HALF_UP);
                                if (a.compareTo(nWarningManagement.getDownAdvancedWarning()) >= 0) {
                                    //高级报警
                                    hntWarnErrorMap.put(uuid, error + ",g");
                                    zjNWarningHnt.setId(uuid);
                                    zjNWarningHnt.setWarningGrade("高级");
                                    BeanUtils.copyProperties(collectPieceDto, zjNWarningHnt);
                                    zjNWarningHnt.setMixingStation(collectPieceDto.getName());
                                    zjNWarningHnt.setType(collectDosage.getMaterial());
                                    zjNWarningHnt.setInsterTime(DateUtils.getNowDate());
                                    zjNWarningHnt.setParentPkId(collectDosage.getParentPkId());
                                    zjNWarningHnt.setError(errors.toString() + "%");
                                    // 高级预警加处置状态为待处置。
                                    zjNWarningHnt.setDisposalStatus(1);
                                    // 盘序号
                                    zjNWarningHnt.setSerial(collectPieceDto.getSerial());
                                    zjNWarningHntMapper.insert(zjNWarningHnt);
                                } else if (a.compareTo(nWarningManagement.getDownMiddleWarning()) >= 0 && a.compareTo(nWarningManagement.getUpMiddleWarning()) == -1) {
                                    //中级报警
                                    hntWarnErrorMap.put(uuid, error + ",z");
                                    zjNWarningHnt.setId(uuid);
                                    zjNWarningHnt.setWarningGrade("中级");
                                    BeanUtils.copyProperties(collectPieceDto, zjNWarningHnt);
                                    zjNWarningHnt.setMixingStation(collectPieceDto.getName());
                                    zjNWarningHnt.setType(collectDosage.getMaterial());
                                    zjNWarningHnt.setInsterTime(DateUtils.getNowDate());
                                    zjNWarningHnt.setParentPkId(collectDosage.getParentPkId());
                                    zjNWarningHnt.setError(errors.toString() + "%");
                                    // 盘序号
                                    zjNWarningHnt.setSerial(collectPieceDto.getSerial());
                                    zjNWarningHntMapper.insert(zjNWarningHnt);
                                } else if (a.compareTo(nWarningManagement.getDownLowWarning()) >= 0 && a.compareTo(nWarningManagement.getUpLowWarning()) == -1 && errors.compareTo(BigDecimal.ZERO) != 0) {
                                    //初级报警
                                    hntWarnErrorMap.put(uuid, error + ",c");
                                    zjNWarningHnt.setId(uuid);
                                    zjNWarningHnt.setWarningGrade("初级");
                                    BeanUtils.copyProperties(collectPieceDto, zjNWarningHnt);
                                    zjNWarningHnt.setMixingStation(collectPieceDto.getName());
                                    zjNWarningHnt.setType(collectDosage.getMaterial());
                                    zjNWarningHnt.setInsterTime(DateUtils.getNowDate());
                                    zjNWarningHnt.setParentPkId(collectDosage.getParentPkId());
                                    zjNWarningHnt.setError(errors.toString() + "%");
                                    // 盘序号
                                    zjNWarningHnt.setSerial(collectPieceDto.getSerial());
                                    zjNWarningHntMapper.insert(zjNWarningHnt);
                                }
                            }
                        }
                    }
                }
            }
            ss = collectPieceDto.getName() + "(" + com.alibaba.fastjson2.util.DateUtils.toString(product.getProdTimB()) + ")的" + (collectPieceDto.getProjName() == null ? " " : collectPieceDto.getProjName()) + (collectPieceDto.getConsPos() == null ? " " : collectPieceDto.getConsPos()) + "的" + collectPieceDto.getRecipe() + "的";
        }
        //保存配比值、误差值及误差百分比；
        baseMapper.updateBatchById(collectDosages);

        //查询短信开关是否开启；
        List<ZjNWarningUsingVo> warnintUsing = warningUsingMapper.selectByStationCode(product.getStationCode());
        if (warnintUsing == null || warnintUsing.size() == 0) {
            log.info("test/7发送短信失败");
            return "发送短信失败";
        } else {
            log.info("******************************************************warnintUsing.size:" + warnintUsing.size());
            ZjNWarningUsingVo zjNWarningUsingVo = warnintUsing.get(0);
            log.info("******************************************************zjNWarningUsingVo:" + JsonUtils.toJsonString(zjNWarningUsingVo));
            if (zjNWarningUsingVo.getUsingMsgHnt() == 0) {
                log.info("test/8混凝土短信预警配置关闭");
                return "混凝土短信预警配置关闭";
            }
        }
        String s1 = "";
        String s2 = "";
        String s3 = "";
        List<String> elementaryList = new ArrayList<>();
        List<String> intermediateList = new ArrayList<>();
        List<String> advancedList = new ArrayList<>();
        List<ZjNWarningHnt> zjNWarningHnts = zjNWarningHntMapper.selectByPkId(pkIds);
        if (zjNWarningHnts.size() > 0) {
//            的第------盘
//            第175389盘小石子、外加剂3、大石子、水、第112盘大石子、外加剂3、第3盘外加剂3、第4盘外加剂3、水、小石子、大石子、小石子、水、水、小石子、大石子、水、大石子、外加剂3、小石子产生了初级预警.
            for (ZjNWarningHnt nWarningHnt : zjNWarningHnts) {
                String parentPkId = nWarningHnt.getParentPkId().toString();
                String error = hntWarnErrorMap.get(nWarningHnt.getId());
                String[] split = null;
                if (error != null) {
                    split = error.split(",");
                    error = "误差" + split[0];
                }
//                String serial = serialMap.get(nWarningHnt.getId());
//                String[] splits = null;
//                if (serial != null) {
//                    splits = serial.split(",");
//                }
                if (nWarningHnt.getWarningGrade().equals("初级")) {
                    if (s1.indexOf("第" + nWarningHnt.getSerial() + "盘") == -1) {
                        s1 = s1 + "第" + nWarningHnt.getSerial() + "盘" + nWarningHnt.getType() + (split != null && "c".equals(split[1]) ? error : "") + "超出上下限" + nWarningHnt.getError() + "、";
                    } else {
                        s1 = s1 + nWarningHnt.getType() + (split != null && "c".equals(split[1]) ? error : "") + "超出上下限" + nWarningHnt.getError() + "、";
                    }
                    elementaryList.add(nWarningHnt.getId());
                } else if (nWarningHnt.getWarningGrade().equals("中级")) {
                    if (s2.indexOf("第" + nWarningHnt.getSerial() + "盘") == -1) {
                        s2 = s2 + "第" + nWarningHnt.getSerial() + "盘" + nWarningHnt.getType() + (split != null && "z".equals(split[1]) ? error : "") + "超出上下限" + nWarningHnt.getError() + "、";
                    } else {
                        s2 = s2 + nWarningHnt.getType() + (split != null && "z".equals(split[1]) ? error : "") + "超出上下限" + nWarningHnt.getError() + "、";
                    }
                    intermediateList.add(nWarningHnt.getId());
                } else if (nWarningHnt.getWarningGrade().equals("高级")) {
                    if (s3.indexOf("第" + nWarningHnt.getSerial() + "盘") == -1) {
                        s3 = s3 + "第" + nWarningHnt.getSerial() + "盘" + nWarningHnt.getType() + (split != null && "g".equals(split[1]) ? error : "") + "超出上下限" + nWarningHnt.getError() + "、";
                    } else {
                        s3 = s3 + nWarningHnt.getType() + (split != null && "g".equals(split[1]) ? error : "") + "超出上下限" + nWarningHnt.getError() + "、";
                    }
                    advancedList.add(nWarningHnt.getId());
                }

            }
        } else {
            sd = "该条数据没有产生报警!";
            productMapper.updateByPkId(pkId);
            log.info("test/22222222222222222222");
            return sd;
        }

        String warnValCon = "";
        String ok = "短信发送成功";
        if (s1 != "") {
            s11 = ss + s1.substring(0, s1.length() - 1) + "产生了初级预警.";
            warnValCon = "1";
            log.info("************初级******************************************selectWarnValCon前warnValCon：" + warnValCon + "----deptId:" + deptId);
            List<String> receiveAddr = messageService.selectWarnValCon(warnValCon, deptId);
            if (receiveAddr != null && receiveAddr.size() > 0) {
                log.info("********************************初级**********************receiveAddr:" + JsonUtils.toJsonString(receiveAddr));
                int send = zjNWarningUsingService.send(receiveAddr, s11);
                if (send == 1) {
                    for (String elementary : elementaryList) {
                        ZjNWarningHnt zjNWarningHnt1z = new ZjNWarningHnt();
                        zjNWarningHnt1z.setSend("发送失败");
                        zjNWarningHnt1z.setMessage(s11);
                        zjNWarningHnt1z.setId(elementary);
                        zjNWarningHntMapper.updateById(zjNWarningHnt1z);
                    }
                } else {
                    for (String elementary : elementaryList) {
                        ZjNWarningHnt zjNWarningHnt1z = new ZjNWarningHnt();
                        zjNWarningHnt1z.setSend("发送成功");
                        zjNWarningHnt1z.setMessage(s11);
                        zjNWarningHnt1z.setId(elementary);
                        zjNWarningHntMapper.updateById(zjNWarningHnt1z);
                    }
                }
            } else {
                log.info("初级预警：没有查到要发送短信的手机号");
            }
        }
        if (s2 != "") {
            s12 = ss + s2.substring(0, s2.length() - 1) + "产生了中级预警.";
            warnValCon = "2";
            log.info("*******************中级***********************************selectWarnValCon前warnValCon：" + warnValCon + "----deptId:" + deptId);
            List<String> receiveAddr = messageService.selectWarnValCon(warnValCon, deptId);
            if (receiveAddr != null && receiveAddr.size() > 0) {
                log.info("**********************************中级********************receiveAddr:" + JsonUtils.toJsonString(receiveAddr));
                int send = zjNWarningUsingService.send(receiveAddr, s12);
                if (send == 1) {
                    for (String intermediate : intermediateList) {
                        ZjNWarningHnt zjNWarningHnt1z = new ZjNWarningHnt();
                        zjNWarningHnt1z.setSend("发送失败");
                        zjNWarningHnt1z.setId(intermediate);
                        zjNWarningHnt1z.setMessage(s12);
                        zjNWarningHntMapper.updateById(zjNWarningHnt1z);
                    }
                } else {
                    for (String intermediate : intermediateList) {
                        ZjNWarningHnt zjNWarningHnt1z = new ZjNWarningHnt();
                        zjNWarningHnt1z.setSend("发送成功");
                        zjNWarningHnt1z.setMessage(s12);
                        zjNWarningHnt1z.setId(intermediate);
                        zjNWarningHntMapper.updateById(zjNWarningHnt1z);
                    }
                }
            } else {
                log.info("中级预警：没有查到要发送短信的手机号");
            }
        }
        if (s3 != "") {
            s13 = ss + s3.substring(0, s3.length() - 1) + "产生了高级预警.";
            warnValCon = "3";
            log.info("**************************高级****************************selectWarnValCon前warnValCon：" + warnValCon + "----deptId:" + deptId);
            List<String> receiveAddr = messageService.selectWarnValCon(warnValCon, deptId);
            if (receiveAddr != null && receiveAddr.size() > 0) {
                log.info("***************************************高级***************receiveAddr:" + JsonUtils.toJsonString(receiveAddr));
                int send = zjNWarningUsingService.send(receiveAddr, s13);
                if (send == 1) {
                    for (String advanced : advancedList) {
                        ZjNWarningHnt zjNWarningHnt1z = new ZjNWarningHnt();
                        zjNWarningHnt1z.setSend("发送失败");
                        zjNWarningHnt1z.setMessage(s13);
                        zjNWarningHnt1z.setId(advanced);
                        zjNWarningHntMapper.updateById(zjNWarningHnt1z);
                    }
//                    return erroy;
                } else {
                    for (String advanced : advancedList) {
                        ZjNWarningHnt zjNWarningHnt1z = new ZjNWarningHnt();
                        zjNWarningHnt1z.setSend("发送成功");
                        zjNWarningHnt1z.setMessage(s13);
                        zjNWarningHnt1z.setId(advanced);
                        zjNWarningHntMapper.updateById(zjNWarningHnt1z);
                    }
//                    return ok ;
                }
            } else {
                log.info("高级预警：没有查到要发送短信的手机号");
            }
        }
        //更新主表状态
        productMapper.updateByPkId(pkId);
        return ok;
    }


    @Override
    public String warning() {
        String test = "";
        String erroy =  "没有发现未预警信息";
        List<CollectProduct> collectProducts = productMapper.selectByList();
        if (collectProducts.size() > 0){
            for (CollectProduct collectProduct : collectProducts) {
                test = test(String.valueOf(collectProduct.getPkId()));
            }
        }else {
            return erroy;
        }
        return test;
    }

    @Override
    public R handleCorrect(String pkId) {
        List<CollectPieceVo> collectPieceVos = pieceMapper.queryPage(null, pkId);
        for (CollectPieceVo collectPieceVo : collectPieceVos) {
            List<CollectDosage> collectDosages = pieceMapper.selectListByPkId(collectPieceVo.getPkId());
            for (CollectDosage d : collectDosages) {
                d.setScale(d.getPlanAmnt());
                d.setUpdateTime(new Date());
                d.setErrorValue(d.getFactAmnt() - (d.getPlanAmnt()));
                d.setPercentError((d.getFactAmnt() - d.getPlanAmnt()) / d.getPlanAmnt() * 100);
            }
            baseMapper.updateBatchById(collectDosages);
        }
        return R.ok();
    }

    /**
     * 修改消耗信息
     */
    @Override
    public Boolean updateByBo(CollectDosageBo bo) {
        CollectDosage update = BeanUtil.toBean(bo, CollectDosage.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CollectDosage entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除消耗信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<CollectDosage> queryByPieceId(Long pieceId) {
        QueryWrapper<CollectDosage> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_pk_id", pieceId);
        return baseMapper.selectList(wrapper);
    }
}
